// document.writeln("<script type='text/javascript' src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js'></script>");
// document.writeln("<script type='text/javascript' src='https://rawgit.com/schmich/instascan-builds/master/instascan.min.js'></script>");
// document.writeln("<script type='text/javascript' src='/static/cews_static/vendor/instascan/instascan.min.js'></script>");
var instascan;
$(function () {
    let is_psu, is_meter = false
    function getCookie(name) {
        let cookieValue = null;
        if (document.cookie && document.cookie !== '') {
            const cookies = document.cookie.split(';');
            for (let i = 0; i < cookies.length; i++) {
                const cookie = cookies[i].trim();
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) === (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }

    function aiDisplayControl(is_psu,is_meter){
        const eformContainer = $('#eform_container')
        const aiContainer = $('#aiContainer')
        const psuUI = $('#psuUI')
        const meterUI = $('#meterUI')
        if (is_psu || is_meter){
            // ai display
            eformContainer.removeClass('col-12')
            eformContainer.addClass('col-10')
            aiContainer.removeClass('d-none')
        }else{
            // ai should not display
            eformContainer.removeClass('col-10')
            eformContainer.addClass('col-12')
            aiContainer.addClass('d-none')
        }
        // ai components on/off
        if (is_meter){
            meterUI.removeClass('d-none')
        }else{
            meterUI.addClass('d-none')
        }

        if (is_psu){
            psuUI.removeClass('d-none')
        }else{
            psuUI.addClass('d-none')
        }

    }
    
    let getIMTE = function (imte_no, cb) {
        axios({
            method: 'get',
            url: `${imte_api_url}${imte_no}`,
        }).then(res => {
            cb(res)
        })
    }

    let insertIMTE = (imte_no, due_date) => {
        data = new FormData()
        // let d = new Date(due_date)
        // let due_date_string = `${d.getFullYear()}-${d.getMonth() + 1}-${d.getDate()}`
        data.append('imte_no', imte_no)
        data.append('due_date', due_date)
        return axios.post(set_imte_url,
            data,
            {
                headers: {
                    'X-CSRFToken': getCookie('csrftoken'),
                    'X-Requested-With': 'XMLHttpRequest'

                }
            })
    }

    let dropIMTE = (imte_no) => {
        data = new FormData()
        data.append('imte_no', imte_no)
        return axios.post(delete_imte_url,
            data,
            {
                headers: {
                    'X-CSRFToken': getCookie('csrftoken'),
                    'X-Requested-With': 'XMLHttpRequest'
                }
            })
    }

    let dropUi = imte_no => {
        $(`#tr-${imte_no}`).remove()
    }

    $(document).on('click', '.imte-delete', function () {
        let imte_no = $(this).data('imte')
        console.log('delete')
        console.log(imte_no)
        dropIMTE(imte_no)
            .then(res => {
                if (res.err) {
                    return
                }
                dropUi(imte_no)
            })

    })

    let appendToUI = function (imte_no,due_date) {
        $('#imte-tbody').append(
            `
            <tr id="tr-${imte_no}">
            <td>
            ${imte_no}
            </td>
            <td>
            ${due_date}
            </td>
            <td class="text-center">
                <button type="button" class="btn btn-sm imte-delete px-2 py-2  btn-primary" data-imte="${imte_no}"><i class="fa fa-times" aria-hidden="true"></i></button>
            </td>
            </tr>
            `
        )
    }

    function setAlert(content) {
        let html = `
        <div id="scan_modal__alert" class="alert alert-warning mb-0 alert-dismissible fade show" role="alert">
        <button type="button" class="close" data-dismiss="alert" aria-label="Close">
        <span aria-hidden="true">&times;</span>
        </button>
        <strong id="scan_modal__alert__content">${content}</strong> 
        </div>
        `
        $('#scan_modal__alert').prepend(html)
    }

    function parseQRCODE(qr_json){
        try {
            qr_json = qr_json.replaceAll("'", '"')
            console.log(qr_json)
            qr_json = JSON.parse(qr_json)
        } catch (err) {
            console.log(err)
            qr_json = false
            setAlert('Incorrect QR Code Format')
        }
        return qr_json
    }

    function processResult(qr_json){
        let due_date = qr_json.SN.replaceAll("Due Date:","");
        let d;
        
        try{
            d = new Date(due_date)
        }catch(err){
            setAlert(`Incorrect Date Format ${qr_json}`)
            return
        }

        let due_date_string = `${d.getFullYear()}-${d.getMonth() + 1}-${d.getDate()}`
        insertIMTE(qr_json.CAT,due_date_string).then(response=>{
            let data = response.data
            if (data.ack){
                appendToUI(qr_json.CAT,due_date_string)
                $('#scan_modal').modal('hide')
            }
            if (data.ack==false && data.err){
                setAlert(data.err)
                return
            }
        })
    }

    instascan = function () {
        $("#preview").show();
        $("#closecam").show();

        let scanner = new Instascan.Scanner({ video: document.getElementById('preview'), mirror: false, });
        scanner.addListener('scan', function (content) {
            // alert(content);
            console.log(content)
            let qr_json = parseQRCODE(content);
            console.log(qr_json)
            if (qr_json != false) {
                processResult(qr_json);
            }
        });
        Instascan.Camera.getCameras().then(function (cameras) {
            // console.log("check camera");
            console.log(cameras.length);
            if (cameras.length > 0) {
                scanner.start(cameras[cameras.length - 1]);
            } else {
                setAlert('No cameras found.');
            }
        }).catch(function (e) {
            console.error(e);
        });

        $('#scan_modal').on('hide.bs.modal', function () {
            try {
                $('#scan_modal__alert').html('')
                scanner.stop()
            } catch {
                console.log("Erron while stopping scanner.")
            }
        })
        // $( "#closecam" ).click(function() {
        //     scanner.stop();
        //     $("#preview").hide();
        //     $("#closecam").hide();
        // })

    }
})
